package middleware

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"alarm_service/common"

	"alarm_service/common/http/httputil"

	"github.com/gin-gonic/gin"
	"zhiyun-tech.com/servers/pkg/logger"
)

// 统计路由日志的中间件
func ApiLog(topic, apiType string, onlyProduction bool) gin.HandlerFunc {
	p, _ := ants.NewPoolWithFunc(20, func(i interface{}) {
		jsonStr := i.(string)
		//logger.Println("RecordToCkLog:", topic, jsonStr, onlyProduction)
		isInternal := true
		if apiType == "dj" || apiType == "djAdmin" || apiType == "guitar" {
			isInternal = false
		}
		err := common.RecordToCkLog(topic, jsonStr, onlyProduction, isInternal)
		if err != nil {
			logger.Errorln("ApiLog RecordToCkLog err:", err)
			return
		}
	})
	//defer p.Release()

	return func(c *gin.Context) {
		st := time.Now()
		c.Next()
		if c.Request.RequestURI != "" && strings.Contains(c.Request.RequestURI, "/health") {
			return
		}
		dt := int(time.Now().Sub(st) / time.Millisecond)
		m := make(map[string]interface{})
		headersMap := make(map[string]string)
		for k, v := range c.Request.Header {
			headersMap[k] = strings.Join(v, ",")
		}
		headersMap["Api-Type"] = apiType         //记录一下Api的类型
		headersMap["Ts"] = fmt.Sprintf("%d", dt) //接口调用时间
		headerStr, _ := json.Marshal(headersMap)
		m["headers"] = string(headerStr)
		m["url"] = c.Request.RequestURI
		m["method"] = c.Request.Method
		m["body"] = c.Request.PostForm.Encode()
		userId, _ := strconv.Atoi(getUserId(c))
		m["userId"] = userId
		m["ip"] = httputil.GetClientIP(c)
		jsonStr, err := json.Marshal(m)
		if err != nil {
			logger.Errorln("ApiLog Marshal err:", err)
			return
		}
		err = p.Invoke(string(jsonStr))
		if err != nil {
			logger.Errorln("ApiLog Invoke err:", err)
			return
		}
	}
}

func getUserId(c *gin.Context) string {
	id := c.Query("userId")
	if strings.TrimSpace(id) == "" {
		id = c.Query("userid")
	}
	if strings.TrimSpace(id) == "" {
		id = c.Query("user_id")
	}
	if strings.TrimSpace(id) == "" {
		id = c.GetHeader("X-ZY-USERID")
	}
	if strings.TrimSpace(id) == "" {
		id = c.GetHeader("user_id")
	}
	if strings.TrimSpace(id) == "" {
		id = c.GetHeader("userId")
	}
	if strings.TrimSpace(id) == "" {
		id = "0"
	}
	return id
}
